﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace ES.Shared.Data
{
    [Serializable]
    public class RelationColumnInfoCollection : Collection<RelationColumnInfo>
    {
        public void AddRange(IEnumerable<RelationColumnInfo> items)
        {
            foreach (RelationColumnInfo item in items)
            {
                Add(item);
            }
        }

        public RelationColumnInfo this[string primaryKeyRelationColumnName, string foreignKeyRelationColumnNam]
        {
            get
            {
                RelationColumnInfo found = FindRelationColumnInfo(primaryKeyRelationColumnName, foreignKeyRelationColumnNam).FirstOrDefault();

                if (found == null)
                    throw new KeyNotFoundException();

                return found;
            }
        }

        private IEnumerable<RelationColumnInfo> FindRelationColumnInfo(string primaryKeyRelationColumnName, string foreignKeyRelationColumnName)
        {
            return from item in this
                   where item.PrimaryKeyColumnName.Equals(primaryKeyRelationColumnName, StringComparison.InvariantCultureIgnoreCase) &&
                         item.ForeignKeyColumnName.Equals(foreignKeyRelationColumnName, StringComparison.InvariantCultureIgnoreCase)
                   select item;
        }

        protected override void InsertItem(int index, RelationColumnInfo item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            if (FindRelationColumnInfo(item.PrimaryKeyColumnName, item.ForeignKeyColumnName).Count() == 0)
                base.InsertItem(index, item);
            else
                throw new ArgumentException(string.Format(LanguageResource.Error_DoubleRelationColumnPair, item.PrimaryKeyColumnName, item.ForeignKeyColumnName));
        }

        protected override void SetItem(int index, RelationColumnInfo item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            if (FindRelationColumnInfo(item.PrimaryKeyColumnName, item.ForeignKeyColumnName).Count() == 0)
                base.SetItem(index, item);
            else
                throw new ArgumentException(string.Format(LanguageResource.Error_DoubleRelationColumnPair, item.PrimaryKeyColumnName, item.ForeignKeyColumnName));
        }
    }
}
